package com.zhouyu.nettysvr.dao;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 设备连接管理
 */
@Service
@Log4j2
public class ConnectionDao {

    /**
     * 长连接缓存中心 连接-设备id
     */
    private static volatile  Map<ChannelHandlerContext, String> connectionCache = new ConcurrentHashMap<>(12);

    /**
     * 创建连接
     * @param channelHandlerContext
     */
    public void createConnection(ChannelHandlerContext channelHandlerContext){
       connectionCache.computeIfAbsent(channelHandlerContext, key -> "");
    }

    /**
     * 初始化连接
     * @param channelHandlerContext
     * @param deviceId
     */
    public void initConnection(ChannelHandlerContext channelHandlerContext,String deviceId){
        String device= connectionCache.get(channelHandlerContext);
        if(StringUtils.isEmpty(device)){
            connectionCache.put(channelHandlerContext,deviceId);
        }else {
            //设备不一致
            if(!device.equals(deviceId)){
                log.error("设备咋还不一致呢？");
            }
        }
    }

    /**
     * 根据设备id获取连接
     * @param deviceId
     */
    public ChannelHandlerContext getConnectionByDeviceId(String deviceId){
        ChannelHandlerContext channelHandlerContext=null;
        for (Map.Entry<ChannelHandlerContext, String> entry : connectionCache.entrySet()) {
            entry.getValue().equals(deviceId);
            channelHandlerContext=entry.getKey();
            break;
        }
        return channelHandlerContext;
    }

    public void closeConnectionByDeviceId(String deviceId){
        ChannelHandlerContext connection = getConnectionByDeviceId(deviceId);
        if(connection!=null){
            connection.channel().close();
            connectionCache.remove(connection);
        }
    }

    public void closeConnection(ChannelHandlerContext connection){
        String deviceId = connectionCache.get(connection);
        log.error("设备[{}]断开连接",deviceId);
        connectionCache.remove(connection);
    }
}
